<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace Sun\Html;

class HtmlContainer extends Container implements IHtmlObject {
    protected $attributes;
    protected $tag;
    protected $foot;

    public function __construct($tag, array $attr = array(), $foot = false) {
        parent::__construct();
        $this->foot = $foot;
        $this->attributes = $attr;
        $this->tag = $tag;
    }

    public function SetAttribute($name, $value = null) {
        $this->attributes[$name] = $value;
        return $this;
    }
    public function SetAttributes(array $arr) {
        foreach ($arr as $name => $val) {
            $this->SetAttribute($name, $val);
        }
        return $this;
    }
    public function Attribute($name) {
        return $this->attributes[$name];
    }
    public function ToHtml() {
        $child = $this->HtmlContent();
        $out = "<".$this->tag;

        foreach($this->attributes as $name => $i) {
            $out .= " {$name}=\"{$i}\"";
        }

        $out .= ($child !== "" || $this->foot) ?
            ">{$child}</{$this->tag}>" : " />";
        return $out;
    }
    public function ToJSON() {
        $child = $this->JSONContent();
        $out = "{ tag: \"{$this->tag}\", ";

        $attr = array();
        foreach($this->attributes as $name => $i) {
            $attr[] = "\"{$name}\":\"{$i}\"";
        }
        $out .= "attr: { ".implode(",", $attr)." }, ";
        $out .= "body: ".$child." }";
        return $out;
    }

    public function Copy() {
        $copy = new HtmlContainer($this->tag, $this->attributes);
        foreach ($this->Childs() as $name => $child) {
            $copy->Add($child->Copy(), $name);
        }
        return $copy;
    }

    public function __get($attr) {
        return $this->Attribute($attr);
    }
    public function __set($attr, $val) {
        $this->SetAttribute($attr, $val);
    }
}
